package com.mldong.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mldong.context.constant.ConstantContextHolder;

import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 *
 * url包裹工具
 * @author mldong
 * @date 2023/7/2
 */
public class UrlWrapUtil {
    private UrlWrapUtil() {};

    /**
     * 文件地址包裹处理
     * @param url
     * @return
     */
    public static String wrap(String url) {
        if(StrUtil.isEmpty(url)) return null;
        String imgBaseUrl = ConstantContextHolder.getImgBaseUrl();
        // url1,url2,url3
        // url1;bizType1,url2;bizType2,url3;bizType3
        String [] urls = url.split(",");
        return Arrays.stream(urls).map(item->{
            String bizType = null;
            if(StrUtil.isNotEmpty(item)) {
                String [] splitItem = item.split(";");
                item = splitItem[0];
                if(splitItem.length == 2) {
                    bizType = splitItem[1];
                }
            }
            String wrapUrl = _wrap(imgBaseUrl, item);
            if(StrUtil.isNotEmpty(wrapUrl) && StrUtil.isNotEmpty(bizType)) {
                return wrapUrl +";"+ bizType;
            }
            return wrapUrl;
        }).filter(item->{
            return StrUtil.isNotEmpty(item);
        }).collect(Collectors.joining(","));
    }

    /**
     * 去掉baseUrl
     * @param url
     * @return
     */
    public static String unWrap(String url) {
        if(url == null) return null;
        if(StrUtil.isEmpty(url)) return "";
        String imgBaseUrl = ConstantContextHolder.getImgBaseUrl();
        String [] urls = url.split(",");
        return Arrays.stream(urls).map(item->{
            String bizType = null;
            if(StrUtil.isNotEmpty(item)) {
                String [] splitItem = item.split(";");
                item = splitItem[0];
                if(splitItem.length == 2) {
                    bizType = splitItem[1];
                }
            }
            String unWrapUrl =  _unWrap(imgBaseUrl, item);
            if(StrUtil.isNotEmpty(unWrapUrl) && StrUtil.isNotEmpty(bizType)) {
                return unWrapUrl +";"+ bizType;
            }
            return unWrapUrl;
        }).filter(item->{
            return StrUtil.isNotEmpty(item);
        }).collect(Collectors.joining(","));
    }
    private static String _wrap(String baseUrl,String url){
        if(StrUtil.isEmpty(url)) return null;
        if(url.startsWith("http")) return url;
        return baseUrl + url;
    }
    private static String _unWrap(String baseUrl,String url){
        if(StrUtil.isEmpty(url)) return null;
        return url.replace(baseUrl, "");
    }
    private static final String BASE64_IMAGE_PATTERN = "<img[^>]*src\\s*=\\s*['\"]data:(.+?);base64,(.+?)['\"][^>]*>";
    private static final Pattern pattern = Pattern.compile(BASE64_IMAGE_PATTERN);

    public static String optimizeBase64Images(String content) {
        if(StrUtil.isEmpty(content)) return content;
        Matcher matcher = pattern.matcher(content);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String base64Data = matcher.group(2);
            String mimeType = matcher.group(1);
            String newSrc = saveBase64Image(base64Data, mimeType);
            String imgTag = matcher.group(0);
            String newImgTag = imgTag.replaceFirst("['\"]data:" + Pattern.quote(mimeType) + ";base64," + Pattern.quote(base64Data) + "['\"]", "\"" + newSrc + "\"");
            matcher.appendReplacement(sb, newImgTag);
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    private static String saveBase64Image(String base64Data, String mimeType) {
        byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
        String uploadBasePath = ConstantContextHolder.getUploadBasePath();
        String path = DateUtil.format(new Date(),"yyyyMM") + "/";
        if(StrUtil.isNotEmpty(uploadBasePath)) {
            uploadBasePath = StrUtil.removeSuffix(uploadBasePath,"/");
            uploadBasePath = StrUtil.removePrefix(uploadBasePath,"/");
            path = uploadBasePath + "/"+ path;
        }
        String objectType = "default";
        Long objectId = IdWorker.getId();
        String ext = mimeType.split("/")[1];
        FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
        cn.xuyanwu.spring.file.storage.FileInfo fileInfo = fileStorageService.of(decodedBytes)
                .setPath(path)
                .setSaveFilename(objectId+"."+ext)
                .setObjectId(objectId)
                .setObjectType(objectType)
                .upload();  //将文件上传到对应地方
        return UrlWrapUtil.wrap(fileInfo.getUrl());
    }
}
